from kubernetes import client
from lucommon.logger import lu_logger


# todo 链接池

class KubernetesAPI:
    client = client

    def __init__(self, ca, cert, key, apiserver):
        self._ca = ca
        self._cert = cert
        self._key = key
        self.apiserver = apiserver

        self._configuration: client.Configuration
        self._api_client: client.ApiClient

    def _make_configuration(self):
        configuration = client.Configuration()
        configuration.ssl_ca_cert = self._ca
        configuration.cert_file = self._cert
        configuration.key_file = self._key
        configuration.host = self.apiserver

        lu_logger.debug("connect to apiserver:{}".format(self.apiserver))

        return configuration

    def _make_api(self, api_client):
        self.Api = None

    def _set_api_attr(self):
        r: client.V1APIResourceList = self.Api.get_api_resources()
        self.api_version = r.group_version
        self.api_group = r.group_version.split("/")[0]
        self.kind_list = []
        for resource in r.resources:
            self.kind_list.append(resource.kind)

    def __enter__(self):
        self._configuration = self._make_configuration()
        self._api_client = client.ApiClient(self._configuration)

        self._make_api(self._api_client)

        if self.Api is None:
            raise Exception("override _make_api() before used")

        self._set_api_attr()

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._api_client.close()
